package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.*;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.*;
import com.jy.bo.common.conf.util.HttpUtil;
import com.robert.vesta.util.IdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/3
 * Time: 8:46 下午
 */
@Service
public class CredexPressService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CredexPressService.class);


    @Autowired
    private CeOrdersDao ordersDao;

    @Autowired
    private CePushLogDao pushLogDao;

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @Autowired
    private CeRepaymentLinkDao ceRepaymentLinkDao;

    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("credexpress", this);
    }


    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
            return false;
        }

        CeAgentAccountEntity ceAgentAccountEntity = agentAccountDao.queryAccount(agentAccount.getAccount(), agentAccount.getMerchantCode());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/collect/pending_collect/service_for_collect_bridge";
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json;charset=utf-8");
        JSONObject jsonObject = JSONObject.parseObject(ceAgentAccountEntity.getRequestHeader());
        headers.put("Authorization", jsonObject.getString("Authorization"));
        HashMap<String, String> parameters = new HashMap<>();
        parameters.put("service_name", "getPendingList");
        parameters.put("pageNumber", "1");
        parameters.put("pageSize", "500");
        String fileList = HttpUtil.postPageBodyByHttps(url, headers, new Gson().toJson(parameters));
        if (StringUtils.isEmpty(fileList)) {
            LOGGER.error("== 请求接口数据出错 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return false;
        }

        return true;
    }

    public String getHttps(CeAgentAccountEntity agentAccount, String service_name, String caseId, boolean showPage, String apiUrl) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        CeAgentAccountEntity ceAgentAccountEntity = agentAccountDao.queryAccount(agentAccount.getAccount(), agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + apiUrl;
        LOGGER.info("== 开始请求接口 ==,url:{}", url);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json;charset=utf-8");
        JSONObject jsonObject = JSONObject.parseObject(ceAgentAccountEntity.getRequestHeader());
        headers.put("Authorization", jsonObject.getString("Authorization"));
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        HashMap<String, String> parameters = new HashMap<>();
        parameters.put("service_name", service_name);
        if (showPage) {
            parameters.put("pageNumber", "1");
            parameters.put("pageSize", "500");
        }
        if (!StringUtils.isEmpty(caseId)) {
            parameters.put("caseId", caseId);
        }
        String result = HttpUtil.postPageBodyByHttps(url, headers, new Gson().toJson(parameters));
        return result;
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== CashPocketService 开始刷新数据 ==,account:{}", agentAccount.getAccount());
        updateOrderList(agentAccount);

        LOGGER.info("== 订单数据更新完成 开始更新订单关联数据==，account:{}", agentAccount.getAccount());
        updateOrderDetailInfo(agentAccount);

        LOGGER.info("== 订单关联数据已经更新完成==，account:{}", agentAccount.getAccount());
    }

    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/collect/pending_collect/service_for_collect_bridge";
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);

        Map<String, String> headers = getHeaders(agentAccount);
        headers.put("Content-Type", "application/json;charset=utf-8");
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        HashMap<String, String> parameters = new HashMap<>();
        parameters.put("service_name", "getPendingList");
        parameters.put("pageNumber", "1");
        parameters.put("pageSize", "500");
        String result = HttpUtil.postPageBody(url, headers, new Gson().toJson(parameters));

        if (StringUtils.isEmpty(result)) {
            LOGGER.error("== 请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return;
        }

        Any resultJson = JsonIterator.deserialize(result);
        if (resultJson.get("data") == null) {
            LOGGER.info("== 请求接口数据为空 ==，account:{}", agentAccount.getAccount());
            return;
        }
        List<Any> items = resultJson.get("data").get("list").asList();
        if (CollectionUtils.isEmpty(items)) {
            LOGGER.info("== 请求接口数据为空  item 为空==，account:{}", agentAccount.getAccount());
            return;
        }

        //查询今天该账号的所有有效订单
        List<Integer> statusList = new ArrayList<>();
        statusList.add(OrderStatusEnum.active.getStatus());
        statusList.add(OrderStatusEnum.updated.getStatus());
        statusList.add(OrderStatusEnum.paid_update.getStatus());

        List<CeOrdersEntity> todayOrders = ordersDao.getTodayListByAgent(agentAccount.getAgentCode());

        Map<String, CeOrdersEntity> todayOrderIdMap = new HashMap<>();
        Map<String, CeOrdersEntity> todayCaseIdMap = new HashMap<>();
        todayOrders.forEach(o -> {
            todayOrderIdMap.put(o.getOrderNo(), o);
            todayCaseIdMap.put(o.getCaseId(), o);
        });

        Map<String, Any> refreshCaseMap = new HashMap<>();
        items.forEach(item -> {
            refreshCaseMap.put(item.get("caseId").toString(), item);
        });

        List<String> newCaseIds = new ArrayList<>();
        List<String> dismissCaseIds = new ArrayList<>();

        refreshCaseMap.keySet().forEach(cashId -> {
            if (!todayCaseIdMap.keySet().contains(cashId)) {
                newCaseIds.add(cashId);
            }
        });

        todayCaseIdMap.keySet().forEach(caseId -> {
            if (!refreshCaseMap.keySet().contains(caseId)) {
                dismissCaseIds.add(caseId);
            }
        });

        //处理移除逻辑
        if (CollectionUtils.isEmpty(dismissCaseIds)) {
            LOGGER.info("== 没有需要移除的订单 ==");
        }
        for (String caseId : dismissCaseIds) {
            CeOrdersEntity ceOrdersEntity = todayCaseIdMap.get(caseId);
            if (ceOrdersEntity.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                ceOrdersEntity.setStatus(OrderStatusEnum.updated.getStatus())
                        .setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
                ordersDao.updateByPrimaryKey(ceOrdersEntity);
            }
        }

        //处理新增逻辑
        if (CollectionUtils.isEmpty(newCaseIds)) {
            LOGGER.info("== 没有新增的订单 ==");
        }
        for (String caseId : newCaseIds) {
            String cashInfo = getHttps(agentAccount, "getCaseInfo", caseId, false, "/collect/collecting/service_for_collect_bridge");
            if (StringUtils.isEmpty(cashInfo)) {
                LOGGER.info("== 获取失败 caseInfo==", cashInfo);
                return;
            }

            Any caseInfoResult = JsonIterator.deserialize(cashInfo);
            Any data = caseInfoResult.get("data");

            String loanId = getCurrentLoan(data).get("appId").toString();
            LOGGER.info("==当天没有数活跃数据 获取loanId ==，loanId:{}", loanId);

            String collectionNo = IdUtils.genId() + "";
            CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                    .setAgentCode(agentAccount.getAgentCode())
                    .setMerchantCode(agentAccount.getMerchantCode())
                    .setOrderNo(loanId)
                    .setOrderInfo(refreshCaseMap.get(caseId).toString())
                    .setStatus(OrderStatusEnum.active.getStatus())
                    .setCreateDt(new Date())
                    .setCollectionNo(collectionNo)
                    .setCaseId(caseId);
            ordersDao.insert(ceOrdersEntity);

            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                    .setOrderNo(loanId)
                    .setMerchantCode(agentAccount.getMerchantCode())
                    .setDataKey("caseInfo")
                    .setDetailInfo(data.toString());
            ordersDetailDao.insert(ordersDetailEntity);
        }

        LOGGER.info("== 订单刷新处理完成 ==");
    }

    public static Any getCurrentLoan(Any data) {
        List<Any> billItemList = data.get("billItemList").asList();
        Any loanId = billItemList.get(0);
        if (billItemList.size() > 1) {
            Date applyDate = DateUtil.getDate(billItemList.get(0).get("applyTime").toString(), "yyyy-MM-dd");
            String currentDate = DateUtil.getDate(new Date(), "yyyy-MM-dd");
            if (!applyDate.before(DateUtil.convertStringToDate(currentDate))) {
                loanId = billItemList.get(1);
            }
        }

        return loanId;
    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {

        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;

                String cashInfo = getHttps(agentAccount, "getCaseInfo", order.getCaseId(), false, "/collect/collecting/service_for_collect_bridge");
                if (StringUtils.isEmpty(cashInfo)) {
                    LOGGER.info("== 获取失败 caseInfo==", cashInfo);
                    order.setStatus(OrderStatusEnum.refresh_failed.getStatus());
                    ordersDao.updateByPrimaryKey(order);
                    return;
                }



                Any caseInfoResult = JsonIterator.deserialize(cashInfo);
                Any data = caseInfoResult.get("data");
                String detailInfo = data.toString();

                Any caseInfoJson = JsonIterator.deserialize(detailInfo);
                Any currentLoan = getCurrentLoan(caseInfoJson);
                String remainMoney = currentLoan.get("overdueAmount").toString();
                updateRemainMoney(order.getCollectionNo(), remainMoney);

                CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "caseInfo", order.getOrderNo());
                if (byKeyAndMerchantAndOrderNo == null) {
                    CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                            .setOrderNo(order.getOrderNo())
                            .setMerchantCode(order.getMerchantCode())
                            .setDataKey("caseInfo")
                            .setDetailInfo(detailInfo);
                    ordersDetailDao.insert(ordersDetailEntity);
                } else {
                    byKeyAndMerchantAndOrderNo.setDetailInfo(detailInfo);
                    ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                }

                if (!hasDetailData) {
                    List<Any> contactItemList = data.get("contactItemList").asList();
                    try {
                        if (CollectionUtils.isNotEmpty(contactItemList)) {
                            JSONArray contacts = new JSONArray();
                            for (Any vo : contactItemList) {
                                JSONObject j1 = new JSONObject();
                                j1.put("name", vo.get("name").toString());
                                j1.put("phone", vo.get("mobile").toString());
                                contacts.add(j1);
                            }
                            JSONObject jsonData = new JSONObject();
                            jsonData.put("contacts", contacts);

                            String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                            LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);

                            CeOrdersDetailEntity contactInfoEntity = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());
                            if (contactInfoEntity == null) {
                                CeOrdersDetailEntity ordersDetailEntity1 = new CeOrdersDetailEntity()
                                        .setOrderNo(order.getOrderNo())
                                        .setMerchantCode(order.getMerchantCode())
                                        .setDataKey("contactUrl")
                                        .setDetailInfo(contactUrl);
                                ordersDetailDao.insert(ordersDetailEntity1);
                            } else {
                                contactInfoEntity.setDetailInfo(contactUrl);
                                ordersDetailDao.updateByPrimaryKey(contactInfoEntity);
                            }
                        }
                    } catch (Exception e) {
                        LOGGER.error("== 通讯录转换错误 ==", e);
                    }

                    order.setSyncStatus(OrderSyncStatusEnum.waiting.getStatus());
                    order.setDetailStatus(1);
                    ordersDao.updateByPrimaryKey(order);
                }
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                String merchant = JsonIterator.deserialize(order.getOrderInfo()).get("merchant").toString();
                ClOrderReceiveRequest request = new ClOrderReceiveRequest()
                        .setOrderBillNo(order.getCollectionNo())
                        .setTradeNo(order.getCollectionNo())
                        .setProductType(merchant)
                        .setAppName(merchant)
                        .setOriginOrderNo(order.getOrderNo())
                        .setAccount(order.getAgentCode())
                        .setClientCode(order.getMerchantCode())
                        .setProductCode(merchant)
                        .setUserCode(IdUtils.genId() + "");

                CeOrdersDetailEntity caseInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "caseInfo", order.getOrderNo());
                Any caseInfoJson = JsonIterator.deserialize(caseInfo.getDetailInfo());
                Any currentLoan = getCurrentLoan(caseInfoJson);
                String borrowCapital = currentLoan.get("principal").toString();
                String overdueDays = currentLoan.get("overdueDays").toString();
                String lateFee = currentLoan.get("fine").toString();

                String overdueRatio = "0";
                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
                if (!overdueDays.equals("0") && !"0".equals(borrowCapital)) {
                    overdueRatio = new BigDecimal(lateFee).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(borrowCapital), 4, BigDecimal.ROUND_HALF_UP).toString();
                }

                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());
//                Any latestBill = bills.get(bills.size() - 1);
                String remainMoney = currentLoan.get("overdueAmount").toString();

                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(1)
                        .setBorrowCapital(new BigDecimal(currentLoan.get("principal").toString()).multiply(new BigDecimal(1)).toString())
                        .setChannel(merchant)
                        .setCapitalCode(merchant)
                        .setInterest(new BigDecimal(currentLoan.get("interest").toString()).multiply(new BigDecimal(1)).toString())
                        .setDeductAmount("0")
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee("0")
                        .setLateServiceFee(new BigDecimal(currentLoan.get("collectFee").toString()).add(new BigDecimal(currentLoan.get("channelFee").toString())).toString())
                        .setReceivedCapital(new BigDecimal(new BigDecimal(borrowCapital).toString()).multiply(new BigDecimal(1)).toString())
                        .setPaidAmount("0")
                        .setReceivedDate(currentLoan.get("applyTime").toString())
                        .setRepaymentDate(currentLoan.get("dueDate").toString())
                        .setRemainMoney(new BigDecimal(remainMoney).multiply(new BigDecimal(1)).toString())
                        .setTotalMoney(new BigDecimal(remainMoney).multiply(new BigDecimal(1)).toString());

                request.setOrderInfo(orderInputVo);

                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());
                CeOrdersDetailEntity contactUrl = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());

                List<Any> contactItemList = caseInfoJson.get("contactItemList").asList();
                List<String> name = Lists.newArrayList();
                List<String> mobile = Lists.newArrayList();
                contactItemList.forEach(item -> {
                    if (item.get("relation").toString().equalsIgnoreCase("father") || item.get("relation").toString().equalsIgnoreCase("mother")) {
                        name.add(item.get("name").toString());
                        mobile.add(item.get("mobile").toString());
                    } else {
                        name.add(item.get("name").toString());
                        mobile.add(item.get("mobile").toString());
                    }

                    if (name.size() > 3) {
                        return;
                    }
                });
                if (name.size() == 1) {
                    name.add(contactItemList.get(2).get("name").toString());
                    mobile.add(contactItemList.get(2).get("mobile").toString());
                }
                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo()
                        .setUserLanguage(caseInfoJson.get("language").toString())
                        .setAadhaarNo("no-data")
                        .setPanCardNo(caseInfoJson.get("pan").toString())
                        .setAddress(caseInfoJson.get("states").toString() + " " + caseInfoJson.get("city").toString() + " " + caseInfoJson.get("address").toString())
                        .setBirthday("1990-01-01")
                        .setCity(caseInfoJson.get("city").toString())
                        .setState(caseInfoJson.get("states").toString())
                        .setEmail(caseInfoJson.get("email").toString())

                        .setContact1Mobile(mobile.get(1))
                        .setContact1Name(name.get(1))
                        .setContact1Relative(1)

                        .setContact2Mobile(mobile.get(2))
                        .setContact2Name(name.get(2))
                        .setContact2Relative(6)

                        .setEducation(0)
                        .setKycNo("no-data")
                        .setMobile(caseInfoJson.get("mobile").toString())

                        .setMarriedStatus(0)
                        .setName(caseInfoJson.get("firstName").toString() + " " + caseInfoJson.get("middleName").toString() + " " + caseInfoJson.get("lastName").toString())
                        .setPinCode("no-data")

                        .setSex(0)
                        .setContactUrl(contactUrl.getDetailInfo());

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity()
                            .setCollectionNo(order.getCollectionNo())
                            .setDetailInfo(JsonStream.serialize(request))
                            .setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    /**
     * 获取新的借贷信息的详细内容是需要 在这个方法执行之前的
     *
     * @param agentAccount
     */
    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        waitingPaidCheckOrders.forEach(order -> {
            LOGGER.info("== 检查订单支付情况==,orderNo:{}", order.getOrderNo());
            CeOrdersDetailEntity caseInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "caseInfo", order.getOrderNo());
            Any currentLoan = getCurrentLoan(JsonIterator.deserialize(caseInfo.getDetailInfo()));

            boolean paidClear = "0".equals(currentLoan.get("overdueAmount").toString());
            if (paidClear) {
                order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                order.setStatus(OrderStatusEnum.paid_update.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }

        });
    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                String paidAmount = "99999";
                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount("0")
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });


    }


    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统 ==");
//        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_remove.getStatus());
//        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
//            LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 没有需要移除的订单==");
//            return;
//        }
//
//        LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 有数据需要移除==,size:{}", todayListBySyncStatusAndAgent.size());
//        todayListBySyncStatusAndAgent.forEach(order -> {
//            try {
//                String paidAmount = "0";
//                ClRepaymentRequest request = new ClRepaymentRequest()
//                        .setDeductAmount("0")
//                        .setOrderBillNo(order.getCollectionNo())
//                        .setPaidAmount(paidAmount)
//                        .setPaidStatus(2)
//                        .setPaidType(1)
//                        .setRepayBizNo(IdUtils.genId() + "")
//                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
//                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
//                        .setTotalDeductAmount("0")
//                        .setTotalPaidAmount(paidAmount)
//                        .setTradeNo(order.getCollectionNo());
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.set("Content-Type", "application/json;charset=utf-8");
//
//                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
//                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl()_remove, requestPush, String.class);
//                String responseStr = responseEntity.getBody().toString();
//                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl()_remove);
//                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
//                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_success.getStatus());
//                } else {
//                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//                }
//            } catch (Exception e) {
//                LOGGER.error("=======  推送collection请求结果 error  ======", e);
//                order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//            }
//            ordersDao.updateByPrimaryKey(order);
//        });


    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }

    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {

        CredexPressCollectionTagEnum currentTag = CredexPressCollectionTagEnum.RNR_V2;

        for (CredexPressCollectionTagEnum e : CredexPressCollectionTagEnum.values()) {
            if (e.getType().equals(ceCommentPushLogEntity.getTargetType())) {
                currentTag = e;
            }
        }

        LOGGER.info("== 开始同步催记到甲方 ==");
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
        CeOrdersDetailEntity emergencyContactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(ceCommentPushLogEntity.getMerchantCode(), "caseInfo", ceCommentPushLogEntity.getOriginNo());
        Any detailInfo = JsonIterator.deserialize(emergencyContactInfo.getDetailInfo());
        try {
            String url = ceMerchantEntity.getApiDomain() + "/collect/collecting/service_for_collect_bridge";
            LOGGER.info("== 开始请求接口 ==,url:{}", url);

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json;charset=utf-8");
            JSONObject jsonObject = JSONObject.parseObject(account.getRequestHeader());
            headers.put("Authorization", jsonObject.getString("Authorization"));
            LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

            HashMap<String, String> parameters = new HashMap<>();
            parameters.put("service_name", "saveLog");
            parameters.put("status", currentTag.getCpType().toString());
            parameters.put("caller", "");
            parameters.put("relation", "self");
            parameters.put("remark", currentTag.getShortDesc());
            parameters.put("mobile", detailInfo.get("mobile").toString());
            parameters.put("name", detailInfo.get("firstName").toString() + "_" + detailInfo.get("middleName").toString() + "_" + detailInfo.get("lastName").toString());

            CeOrdersEntity oneByOrderNo = ordersDao.getOneByOrderNo(emergencyContactInfo.getOrderNo());
            String cashId = JsonIterator.deserialize(oneByOrderNo.getOrderInfo()).get("caseId").toString();
            parameters.put("caseId", cashId);
            String result = HttpUtil.postPageBodyByHttps(url, headers, new Gson().toJson(parameters));

            LOGGER.info("== 开始同步催记到甲方 ==,res:{}", result);

            return "2000".equals(JsonIterator.deserialize(result).get("code").toString());
        } catch (Exception e) {
            LOGGER.error("== 开始同步催记到甲方 exception==", e);
        }
        return false;
    }


    @Override
    public Map<String, String> getHeaders(CeAgentAccountEntity agentAccount) {
        String requestHeader = agentAccount.getRequestHeader();
        Map headers = Maps.newHashMap();
        if (StringUtils.isNotEmpty(requestHeader)) {
            Map<String, Any> stringAnyMap = JsonIterator.deserialize(requestHeader).asMap();
            stringAnyMap.keySet().forEach(k -> {
                headers.put(k, stringAnyMap.get(k).toString());
            });
        }

        return headers;
    }

    public static void main(String[] args) {
        Date applyDate = DateUtil.getDate("2022-01-17", "yyyy-MM-dd");
        String currentDate = DateUtil.getDate(new Date(), "yyyy-MM-dd");
        if (applyDate.before(DateUtil.convertStringToDate(currentDate))) {
            System.err.println(11);
        }

        System.err.println(111);
    }

    @Override
    public String updateRepaymentLink(String collectionNo,boolean isReduce) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeOrdersDetailEntity emergencyContactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(ceOrdersEntity.getMerchantCode(), "caseInfo", ceOrdersEntity.getOrderNo());
        Any detailInfo = JsonIterator.deserialize(emergencyContactInfo.getDetailInfo());
        String url = ceMerchantEntity.getApiDomain() + "/credit/user_base_info/get_repayment_link";
        LOGGER.info("== 开始请求接口 ==,url:{}", url);

        String link="";
        Any currentLoan = getCurrentLoan(detailInfo);
        Map<String, String> headers = getHeaders(account);
        headers.put("Content-Type", "application/json;charset=utf-8");

        JSONObject parameters = new JSONObject();
        parameters.put("app_id", currentLoan.get("appId").toString());
        String result = HttpUtil.postPageBody(url,headers,parameters.toString());
        Any resultJson = JsonIterator.deserialize(result);
        LOGGER.info("== 获取还款链接 ==,result:{}", result);
        if (!resultJson.get("data").toString().equals("")) {
            link = resultJson.get("data").toString();
            LOGGER.info("== 获取还款链接 ==,link:{}", link);
        }
        return link;
    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo,boolean isOpen) {
        return "null";
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        return "";
    }

    @Override
    public String queryPaymentOrderResult(String orderNo,String utr) {
        return "";
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        return null;
    }

    private static String getBirthDayByAge(Integer age) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();

        c.setTime(new Date());
        c.add(Calendar.YEAR, -age);
        Date y = c.getTime();
        return format.format(y);
    }
}
